package com.hd.crdao.activity;

import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.DigitsKeyListener;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hd.crdao.R;
import com.hd.crdao.base.BaseActivity;
import com.hd.crdao.bean.ProductBean;
import com.hd.crdao.config.Constants;
import com.hd.crdao.proxy.SimpleTextChangeWatcher;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.ExpandHeadView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 *
 *@author Administrator
 *@date 2017/8/17 0017
 */

public class SetAmountActivity extends BaseActivity {
    @BindView(R.id.set_amount_head)
    ExpandHeadView mSetAmountHead;
    @BindView(R.id.et_money)
    EditText mEtMoney;
    /*@BindView(R.id.gridview)
    GridView mGridview;*/

    @BindView(R.id.next)
    Button mNext;
    @BindView(R.id.usagelayout)
    TagFlowLayout mUsageLayout;
    @BindView(R.id.t0level)
    CheckBox mT0Level;
    @BindView(R.id.t1level)
    CheckBox mT1Level;
    public String mId;
    public List<ProductBean.ProductListBean> mProductList;
    public SimpleTextChangeWatcher mSimpleTextChangeWatcher;
    public MyTagAdapter mAdapter;
    private String T0Flag;    //费率
    private String flag;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_set_amount;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        dealWithInputMoney();


    }

    /**
     * 初始化checkbox
     */
    private void initCheckBox() {
        //设置checkbox的颜色字体
        final String[] crRates = getIntent().getStringArrayExtra("crRate");
        setMultiColorTextShow(mT0Level, "T+0费率" + crRates[0], Color.parseColor("#999999"), 0, 3);
        setMultiColorTextShow(mT1Level, "T+1费率" + crRates[1], getResources().getColor(R.color.colorAppMain), 0, 3);
        View.OnClickListener mOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v == mT0Level) {  //to被选中时,弹出提示
                    if (TextUtils.equals(T0Flag, "1")) {
                        mT0Level.setChecked(true);
                        mT1Level.setChecked(false);
                        flag = "1";
                    } else {
                        mT0Level.setChecked(false);
                        MyToast.show("暂未开放,敬请期待~!");
                    }
                } else {
                    mT0Level.setChecked(false);
                    mT1Level.setChecked(true);
                    flag = "0";
                }
            }
        };

        mT0Level.setOnClickListener(mOnClickListener);
        mT1Level.setOnClickListener(mOnClickListener);
    }


    /**
     * 设置同一个文本多种颜色处理
     *
     * @param target  目标textview控件
     * @param content 显示内容(不是变色部分)
     * @param color   颜色
     * @param start   从哪里开始
     * @param end     从哪里结束
     */
    private void setMultiColorTextShow(TextView target, String content, int color, int start, int end) {
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(color);
        SpannableString spannableString = new SpannableString(content);
        spannableString.setSpan(foregroundColorSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        target.setText(spannableString);
    }

    /**
     * 对输入金额所做的处理
     */
    private void dealWithInputMoney() {
        mEtMoney.setKeyListener(DigitsKeyListener.getInstance("0123456789."));

        mEtMoney.setFilters(new InputFilter[]{inputFilter, new InputFilter.LengthFilter(10)});

        mSimpleTextChangeWatcher = new SimpleTextChangeWatcher() {
            @Override
            public void afterTextChanged(Editable editable) {
                String inputWord = editable.toString();
                if (!inputWord.contains(".") && inputWord.length() > 7) {
                    MyToast.show("最大金额不能超过9999999.99");

                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //如果输入框为空则不处理
                if (TextUtils.isEmpty(s)) {
                    return;
                }
                //第一个字符不为小数点
                if (s.length() == 1 && s.toString().equals(".")) {
                    mEtMoney.setText("");
                    return;
                }
                int counter = counter(s.toString(), '.');
                if (counter > 1) {
                    //小数点第一次出现的位置
                    int index = s.toString().indexOf('.');
                    mEtMoney.setText(s.subSequence(0, index + 1));
                }
                mEtMoney.setSelection(mEtMoney.getText().toString().length());
            }
        };
        mEtMoney.addTextChangedListener(mSimpleTextChangeWatcher);
    }

    @Override
    protected void initData() {
        //  TextView textview = (TextView) view.findViewById(R.id.tv_desc);


        OkHttpUtils.post().url(Constants.FINDPRODUCTLIST_URL).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("网络开了个小差");
            }

            @Override
            public void onResponse(String response, int id) {
                ALog.d(response);
                Gson gson = new Gson();
                final ProductBean productBean = gson.fromJson(response, ProductBean.class);
                String success = productBean.getSuccess();
                String message = productBean.getMessage();
                if (TextUtils.equals("00", success)) {
                    mProductList = productBean.getProductList();
                    if (mProductList.size() != 0) {
                        mAdapter = new MyTagAdapter(mProductList);
                        mUsageLayout.setAdapter(mAdapter);
                        mAdapter.setSelectedList(0);
                        T0Flag = productBean.getT0Flag();
                        mId = mProductList.get(0).getId();
                        flag="0";   //默认是T1
                        //   T0Flag="1";   该值仅用于测试
                        initCheckBox();
                    }
                } else {
                    MyToast.show(message);
                }
            }
        });


    }

    private class MyTagAdapter extends TagAdapter<ProductBean.ProductListBean> {

        public MyTagAdapter(List<ProductBean.ProductListBean> datas) {
            super(datas);
        }

        @Override
        public View getView(FlowLayout parent, int position, ProductBean.ProductListBean productListBean) {
            TextView textview = (TextView) View.inflate(UIUtils.getContext(), R.layout.item_productlist,
                    null);
            //  TextView textview = (TextView) view.findViewById(R.id.tv_desc);
            textview.setText(productListBean.getPrName());
            textview.setHeight(UIUtils.dip2Px(40));
            textview.setWidth(UIUtils.dip2Px(90));
            textview.setGravity(Gravity.CENTER);
            return textview;
        }
    }

    @Override
    protected void initListener() {
        mSetAmountHead.getHeadViewLeftText().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mSetAmountHead.getHeadViewRightText().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(UIUtils.getContext(), AccountDetailsActivity.class));
            }
        });

        /*mGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mProductListAdapter.changeState(position);
                ProductBean.ProductListBean productListBean = (ProductBean.ProductListBean) mProductListAdapter.getItem(position);
                mId = productListBean.getId();

            }
        });*/
        mUsageLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                /*TextView textView = (TextView) view;
                textView.setTextColor(getResources().getColor(R.color.colorAppMain));*/
                ALog.d(position + "");
                ProductBean.ProductListBean productListBean = mProductList.get(position);
                mId = productListBean.getId();
                return true;
            }
        });
       /* mUsageLayout.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
            @Override
            public void onSelected(Set<Integer> selectPosSet) {
                ALog.d(selectPosSet.toString().substring(1, 2));
            }
        });*/

    }

    @OnClick(R.id.next)
    public void onViewClicked() {
        String money = mEtMoney.getText().toString().trim();
        if (TextUtils.isEmpty(money)) {
            MyToast.show("请输入金额");
            return;
        }
        double realMoney = Double.parseDouble(money);
        ALog.d("" + realMoney);
        if (mUsageLayout.getSelectedList().isEmpty()) {
            MyToast.show("请选择收款用途");
            return;
        } else if (realMoney <= 0) {
            MyToast.show("金额应大于0");
            return;
        } else if (realMoney > 9999999.99) {
            MyToast.show("最大金额不能超过9999999.99");
            return;
        }
        Intent i = new Intent(UIUtils.getContext(), CodePayActivity.class);
        i.putExtra("orderPrice", dealWithNum(String.valueOf(realMoney)));
        i.putExtra("productId", mId);
        i.putExtra("T0Flag", flag);
        startActivity(i);
    }

    /**
     * 确保传过来的金额是保留2位小数
     */
    public String dealWithNum(String money) {
        if (money.contains(".")) {
            int indexOf = money.indexOf(".");
            if (indexOf == money.length() - 2) {
                return money.concat("0");
            } else {
                return money;
            }
        } else {
            return money.concat(".00");
        }

    }


    /**
     * 过滤器
     */
    private InputFilter inputFilter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            // 删除等特殊字符，直接返回
            if (TextUtils.isEmpty(source)) {
                return null;
            }
            String dValue = dest.toString();
            String[] splitArray = dValue.split("\\.");
            if (splitArray.length > 1) {
                String dotValue = splitArray[1];
                // 2 表示输入框的小数位数
                int diff = dotValue.length() + 1 - 2;
                if (diff > 0) {
                    return source.subSequence(start, end - diff);
                }
            }
            return null;
        }
    };

    /**
     * @param s
     * @param c
     * @return
     */
    public int counter(String s, char c) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == c) {
                count++;
            }
        }
        return count;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSimpleTextChangeWatcher != null) {
            mEtMoney.removeTextChangedListener(mSimpleTextChangeWatcher);
        }
    }
}
